package com.example.a001.part12;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.a001.R;

import java.util.List;

public class FlowerAdapter extends RecyclerView.Adapter<FlowerAdapter.ViewHolder> {

    private List<Flower> mFlowerList;

    static class ViewHolder extends RecyclerView.ViewHolder {
        View itemView;
        ImageView flowerImage;
        TextView flowerName;

        public ViewHolder(View view) {
            super(view);
            itemView = view;
            flowerImage = view.findViewById(R.id.flower_image);
            flowerName = view.findViewById(R.id.flower_name);
        }
    }

    public FlowerAdapter(List<Flower> flowerList) {
        mFlowerList = flowerList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.flower_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);

        // 设置点击事件
        setOnClickListeners(holder, view);

        return holder;
    }

    private void setOnClickListeners(final ViewHolder holder, View view) {
        holder.itemView.setOnClickListener(v -> {
            int position = holder.getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                Flower flower = mFlowerList.get(position);

                Toast.makeText(v.getContext(), "You clicked view: " + flower.getName(), Toast.LENGTH_SHORT).show();
            }
        });

        holder.flowerImage.setOnClickListener(v -> {
            int position = holder.getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                Flower flower = mFlowerList.get(position);
                Toast.makeText(v.getContext(), "You clicked image: " + flower.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Flower flower = mFlowerList.get(position);
        holder.flowerImage.setImageResource(flower.getImageId());
        holder.flowerName.setText(flower.getName());
    }

    @Override
    public int getItemCount() {
        return mFlowerList.size();
    }
}
